package server

import (
	"3-6zk/common/models/mysql"
	"3-6zk/common/models/redis"
	"3-6zk/common/proto/user"
	"context"
	"fmt"
	jwt "github.com/golangblogs/gojwt"
	"math/rand"
	"strconv"
	"time"
)

func Login(req *user.LoginReq) (*user.LoginResp, error) {
	val := redis.Rdb.Get(context.Background(), "smsCark"+req.Phone).Val()
	atoi, _ := strconv.Atoi(val)
	if atoi >= 3 {
		return nil, fmt.Errorf("验证码错误三次，冻结一小时")
	}
	get := redis.Rdb.Get(context.Background(), "smslogin"+req.Phone)
	if get.Val() != req.SendSms {
		redis.Rdb.Incr(context.Background(), "smsCark"+req.Phone)
		redis.Rdb.Expire(context.Background(), "smsCark"+req.Phone, time.Minute*60)
		return nil, fmt.Errorf("验证码错误")
	}
	u := mysql.User{}
	getUser, err := u.GetUser(req.Phone)
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if getUser.Phone == "" {
		m := mysql.User{
			Phone:    req.Phone,
			Password: req.Password,
		}
		err = u.Create(&m)
		if err != nil {
			return nil, fmt.Errorf("注册失败")
		}
	}
	if getUser.Password != req.Password {
		return nil, fmt.Errorf("密码错误")
	}
	claims := jwt.CustomClaims{ID: getUser.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, fmt.Errorf("token生成失败")
	}
	return &user.LoginResp{Greet: token}, nil
}

func SendSms(req *user.SendSmsReq) (*user.SendSmsResp, error) {
	i := rand.Intn(9000) + 1000

	//smss, err := pkg.SendSmss(req.Phone, strconv.Itoa(i))
	//if err != nil {
	//	return nil, err
	//}
	//if smss.Body.Message != smss.Body.Code {
	//	return nil, err
	//}
	set := redis.Rdb.Set(context.Background(), "sms"+req.Soures+req.Phone, i, time.Minute*3).Val()
	return &user.SendSmsResp{Code: set}, nil

}
